package com.example.demo.app.validate;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.example.demo.app.model.User;

import lombok.extern.slf4j.Slf4j;


/**
 * 
 * @author Administrator
 * 自定义bean的验证，User
 */
@Slf4j
public class UserValidate implements Validator {

	@Override
	public boolean supports(Class<?> arg0) {
		log.info("ee:"+arg0+","+User.class.isAssignableFrom(arg0));
		return User.class.isAssignableFrom(arg0);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmpty(errors, "userName", "user.userName.required", "用户名不能为空");
		ValidationUtils.rejectIfEmpty(errors, "password", "user.password.required", "密码不能为空");
		ValidationUtils.rejectIfEmpty(errors, "email", "user.email.required", "邮箱不能为空");
		User user = (User) target;
		int length = user.getUserName().length();
		if (length > 20) {
			errors.rejectValue("userName", "user.userName.too_long", "用户名不能超过{20}个字符");
		}
		length = user.getPassword().length();
		if (length < 6) {
			errors.rejectValue("password", "user.password.too_short", "密码太短，不能少于{6}个字符");
		} else if (length > 20) {
			errors.rejectValue("password", "user.password.too_long", "密码太长，不能长于{20}个字符");
		}
		int index = user.getEmail().indexOf("@");
		if (index == -1) {
			errors.rejectValue("email", "user.email.invalid_email", "邮箱格式错误");
		}
	}
}
